using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace LeeFramework.Editor.UISkin
{
    public class EditorUISkin : EditorWindow
    {
        private static GUIStyle _LargeStyle;
        private static GUIStyle _MidStyle;

        private static string _SrcPrefabsRootPath;
        private static string _TarPrefabsRootPath;
        private static string _SrcResRootPath;
        private static string _TarResRootPath;


        [MenuItem("Assets/UISkin", false, 100)]
        public static void UISkin()
        {
            Init();
            GetWindow<EditorUISkin>("UISkin");
        }

        public static void Init()
        {
            _LargeStyle = new GUIStyle(EditorStyles.largeLabel);
            _LargeStyle.fontSize = 25;
            _LargeStyle.alignment = TextAnchor.UpperCenter;
            _LargeStyle.richText = true;

            _MidStyle = new GUIStyle(EditorStyles.boldLabel);
            _MidStyle.fontSize = 15;
            _MidStyle.alignment = TextAnchor.UpperLeft;
            _MidStyle.richText = true;

            _SrcPrefabsRootPath = EditorPrefs.GetString("UISkinSrcPrefabsPath", "Assets/");
            _TarPrefabsRootPath = EditorPrefs.GetString("UISkinTarPrefabsRootPath", "Assets/");
            _SrcResRootPath = EditorPrefs.GetString("UISkinSrcResRootPath", "Assets/");
            _TarResRootPath = EditorPrefs.GetString("UISkinTarResRootPath", "Assets/");
        }

        private void OnGUI()
        {
            GUILayout.Space(10);

            GUILayout.Label("自动换皮", _LargeStyle);

            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            GUILayout.Label("原预制体根路径：", _MidStyle);
            _SrcPrefabsRootPath = GUILayout.TextField(_SrcPrefabsRootPath, GUILayout.Height(30), GUILayout.Width(550));
            GUILayout.Space(10);

            GUILayout.Label("目标预制体根路径：", _MidStyle);
            _TarPrefabsRootPath = GUILayout.TextField(_TarPrefabsRootPath, GUILayout.Height(30), GUILayout.Width(550));
            GUILayout.Space(10);

            GUILayout.Label("原资源根路径：", _MidStyle);
            _SrcResRootPath = GUILayout.TextField(_SrcResRootPath, GUILayout.Height(30), GUILayout.Width(550));
            GUILayout.Space(10);

            GUILayout.Label("目标资源根路径：", _MidStyle);
            _TarResRootPath = GUILayout.TextField(_TarResRootPath, GUILayout.Height(30), GUILayout.Width(550));
            GUILayout.Space(10);

            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            Color oldColor = GUI.backgroundColor;

            GUI.backgroundColor *= new Color(0.5f, 1, 0.5f);
            if (GUILayout.Button("生成", GUILayout.Width(300), GUILayout.Height(35)))
            {
                StartUISkin();
                Close();
            }
            GUI.backgroundColor = oldColor;

            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
        }

        /// <summary>
        /// 开始换皮
        /// </summary>
        private void StartUISkin()
        {
            if (string.IsNullOrEmpty(_SrcPrefabsRootPath))
            {
                Debug.LogError("原预制体根路径为空，请检查...");
                return;
            }
            EditorPrefs.SetString("UISkinSrcPrefabsRootPath", _SrcPrefabsRootPath);

            if (string.IsNullOrEmpty(_TarPrefabsRootPath))
            {
                Debug.LogError("目标预制体根路径为空，请检查...");
                return;
            }
            EditorPrefs.SetString("UISkinTarPrefabsRootPath", _TarPrefabsRootPath);

            if (string.IsNullOrEmpty(_SrcResRootPath))
            {
                Debug.LogError("原资源根路径为空，请检查...");
                return;
            }
            EditorPrefs.SetString("UISkinSrcResRootPath", _SrcResRootPath);

            if (string.IsNullOrEmpty(_TarResRootPath))
            {
                Debug.LogError("目标资源根路径为空，请检查...");
                return;
            }
            EditorPrefs.SetString("UISkinTarResRootPath", _TarResRootPath);

            string[] allPrefabsPath = AssetDatabase.FindAssets("t:prefab");

            foreach (string item in allPrefabsPath)
            {
                string path = AssetDatabase.GUIDToAssetPath(item);
                GameObject srcPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);

                GameObject inspRrefab = GameObject.Instantiate(srcPrefab);

                FindImage(inspRrefab);
                FindAllChild(inspRrefab);

                string newPath = path.Replace(_SrcPrefabsRootPath, _TarPrefabsRootPath);

                SavePrefab(inspRrefab, newPath);
                GameObject.DestroyImmediate(inspRrefab.gameObject);
            }
            AssetDatabase.Refresh();
        }

        private void FindAllChild(GameObject go)
        {
            for (int i = 0; i < go.transform.childCount; i++)
            {
                FindImage(go.transform.GetChild(i).gameObject);
                FindAllChild(go.transform.GetChild(i).gameObject);
            }
        }

        private void FindImage(GameObject go)
        {
            MaskableGraphic mask = go.GetComponent<MaskableGraphic>();
            if (mask != null)
            {
                string assetPath = AssetDatabase.GetAssetPath(mask.mainTexture);

                if (!string.IsNullOrEmpty(assetPath))
                {
                    string newAssetPath = assetPath.Replace(_SrcResRootPath, _TarResRootPath);

                    if (mask is Image)
                    {
                        Image img = mask as Image;

                        img.sprite = AssetDatabase.LoadAssetAtPath<Sprite>(newAssetPath);
                    }
                    else if (mask is RawImage)
                    {
                        RawImage rawImg = mask as RawImage;

                        rawImg.texture = AssetDatabase.LoadAssetAtPath<Texture>(newAssetPath);
                    }
                    else
                    {
                        Debug.LogError("有其他的组件，请检查 : " + go.name);
                    }

                }

            }
        }

        private void SavePrefab(GameObject prefab, string path)
        {
            HasDirectory(path);
            PrefabUtility.SaveAsPrefabAssetAndConnect(prefab, path, InteractionMode.UserAction);
        }

        private bool HasDirectory(string path)
        {
            path = Path.GetDirectoryName(path);
            if (Directory.Exists(path))
            {
                return true;
            }
            else
            {
                Directory.CreateDirectory(path);
                return false;
            }
            return false;
        }

    }
}